package com.dykj.fireFighting.web.devhis;

import com.dykj.fireFighting.api.base.dev.service.IDevHisFilesService;
import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.base.video.service.IVideoService;
import com.dykj.fireFighting.api.base.video.vo.VideoPlayVo;
import com.dykj.fireFighting.api.elasticsearch.devHis.entity.EsDevHis;
import com.dykj.fireFighting.api.elasticsearch.devHis.service.EsDevHisService;
import com.dykj.fireFighting.api.socialUnit.devHis.dto.DevHisDto;
import com.dykj.fireFighting.api.socialUnit.devHis.entity.DevHis;
import com.dykj.fireFighting.api.socialUnit.devHis.service.IDevHisService;
import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.Device;
import com.dykj.fireFighting.api.socialUnit.devicemanger.service.IDeviceService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * 实时报警接口
 *
 * @Author hxb
 * @Date 2021-06-30 14:45:09
 */
@Slf4j
@Api(value = "实时报警接口", tags = {"实时报警接口"})
@RestController
@RequestMapping("/devHisAlarm")
public class DevHisAlarmController {

    @DubboReference
    private IDevHisService devHisService;
    @DubboReference
    private IDeviceService deviceService;
    @DubboReference
    private IVideoService videoService;
    @DubboReference
    private IDevHisFilesService devHisFilesService;
    @DubboReference
    private EsDevHisService esDevHisService;

    /**
     * 已复核记录列表
     *
     * @return
     */
    @AutoLog(value = "实时报警接口-已复核列表查询")
    @ApiOperation(value = "实时报警接口-已复核列表查询", notes = "实时报警接口-已复核列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "deviceCode",value = "用户传输装置唯一编码",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query",name = "bjzt",value = "部件状态id",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "page",value = "页码",dataType = "Integer",required = true),
            @ApiImplicitParam(paramType = "query",name = "limit",value = "每页数据条数",dataType = "Integer",required = true),
            @ApiImplicitParam(paramType = "query",name = "status",value = "状态(0未复核1已复核)",dataType = "String",required = true)
    })
    @GetMapping("/reviewList")
    /* @RequiresPermissions("app/devHisAlarm/list")*/
    public CommonResult queryList(DevHisDto devHisDto) {
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        devHisDto.setUnitId(loginUserVo.getEnterpriseId().toString());
        String tableName="dev_his_";
        if(null !=devHisDto.getSj() && StringUtils.isNotBlank(devHisDto.getSj())){
            String[] strings = devHisDto.getSj().split(",");
            String beginDate=strings[0];
            tableName=tableName+DateUtil.getWeek(beginDate);
        }else{
            tableName = tableName + DateUtil.getYearWeek();
        }
        int count=devHisService.isExistTable(tableName);

        PageVo<DevHis> page = devHisService.queryList(devHisDto,tableName);

        return CommonResult.success(page);
    }

    @GetMapping("/updateRead")
    public CommonResult updateRead(String id,String read){
        DevHis devHis=new DevHis();
        devHis.setId(id);
        devHis.setIsRead(read);
        int i=devHisService.updateDevHis(devHis);
        return CommonResult.success("成功");
    }

    /**
     * 获取图片
     *
     */
    @AutoLog(value = "实时报警接口-获取复核图片")
    @ApiOperation(value = "实时报警接口-获取复核图片", notes = "实时报警接口-获取复核图片")
    @GetMapping("/getImgs")
    public CommonResult getImgs(String id,String sj) {
        try {
            String tableName="dev_his_";
            if(StringUtils.isNotBlank(sj)){
                String[] strings = sj.split(",");
                String beginDate=strings[0];
                tableName=tableName+DateUtil.getWeek(beginDate);
            }else{
                tableName = tableName + DateUtil.getYearWeek();
            }
          List<DataFiles> filesList=devHisFilesService.getImgsByHisId(id,"3",tableName);

            return CommonResult.success(filesList);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("查询失败，请联系管理员");
        }
    }


    /**
     * 实时报警视频播放
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实时报警视频播放")
    @ApiOperation(value = "实时报警视频播放", notes = "实时报警视频播放")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/play/{id}")
    public CommonResult<List<VideoPlayVo>> queryDevHisAlarmPlayList(@PathVariable("id") String id) {
        List<VideoPlayVo> videoPlayVoList = new ArrayList();
        Device device = deviceService.getByDevHisId(id);
        if (StringUtils.isNotBlank(device.getVideoId())) {

            List<String> list = new ArrayList<>(Arrays.asList(device.getVideoId().split(",")));
            for (String videoId : list) {
                VideoPlayVo videoPlayVo = videoService.videoPlay(videoId);
                videoPlayVoList.add(videoPlayVo);
            }
        }
        return CommonResult.success(videoPlayVoList);
    }

    /**
     * 实时报警接口记录列表
     *
     * @param devHisDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @AutoLog(value = "实时报警接口-分页列表查询")
    @ApiOperation(value = "实时报警接口-分页列表查询", notes = "实时报警接口-分页列表查询")
    @GetMapping("/list")
    @ResponseBody
    public CommonResult<PageVo<EsDevHis>> search(DevHisDto devHisDto,
                                                 @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                 @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        String unitId = ShiroUtil.getUser().getEnterpriseId().toString();
        PageVo<EsDevHis> esDevHisPageVo = esDevHisService.queryList(devHisDto.getSj(), devHisDto.getBjzt(), devHisDto.getStatus(), null, unitId,
                pageNum - 1, pageSize,devHisDto.getDevName(),devHisDto.getDevType(),devHisDto.getLx());

        List<EsDevHis> list = esDevHisPageVo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            List<EsDevHis> relationIdList = new ArrayList<>();
            list.stream().forEach(esDevHis -> {
                if (StringUtils.isNotBlank(esDevHis.getRelationId())) {
                    DevHis devHis = devHisService.queryByRelationId(esDevHis.getRelationId());
                    if (devHis != null) {
                        esDevHis.setDevUnitName(devHis.getDevUnitName());
                        esDevHis.setDevName(devHis.getDevName());
                        esDevHis.setDevType(devHis.getDevType());
                    }
                }
                relationIdList.add(esDevHis);
            });
            esDevHisPageVo.setList(relationIdList);
        }
        return CommonResult.success(esDevHisPageVo);
    }
}
